﻿using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

namespace Admin.CYT369.Com.DAL.Services
{
    public class ConfigService : Admin.CYT369.Com.DAL.DbContexts.BaseService<ConfigService>
    {
        public ConfigService() { }

        #region Config
        public IQueryable<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary> GetAppDictionarys(string typeCode = null, string module = null)
        {
            var items = this.Get<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary>();
            if (string.IsNullOrEmpty(module)) {
                items = items.Where(c => c.Module == module);
            }
            
            if (string.IsNullOrEmpty(typeCode))
            {
                items = items.Where(c => c.TypeCode == null || c.TypeCode == string.Empty);
            }
            else
            {
                items = items.Where(c => c.TypeCode == typeCode);
            }


            return items.OrderBy(c=>c.Sequence);
        }

        public Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary GetAppDictionaryByID(int id)
        {
            return base.GetOne<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary>(c => c.Id == id);
        }
        public Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary GetAppDictionaryByTID(string type, int id)
        {
            return base.GetOne<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary>(c => c.DictionaryID == id && c.TypeCode == type);
        }
        public bool DeleteAppDictionary(int id)
        {
            return base.Delete<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary>(c => c.Id == id);
        }

        public bool SaveAppDictionary(Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary appDictionary)
        {
            using (var db = this.Ctx)
            {
                var item = (from o in db.Set<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary>()
                            where o.Id == appDictionary.Id
                            select o).FirstOrDefault();

                if (item == null)
                {
                    db.Set<Admin.CYT369.Com.DAL.Domains.Apps.AppDictionary>().Add(appDictionary);
                }
                else
                {
                    item.DictionaryID = appDictionary.DictionaryID;
                    item.TypeCode = appDictionary.TypeCode;
                    item.Code = appDictionary.Code;
                    item.Name = appDictionary.Name;
                    item.Description = appDictionary.Description;
                    item.Sequence = appDictionary.Sequence;
                }
                db.SaveChanges();

                return true;
            }
        }
        #endregion

    }


}
